package net.swaddy.cxf.rest.clientaccess;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLDecoder;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.junit.Test;

public class RestClientAccess {

	/**the json format returned by the requested rest service url.
	{
   "authenticationResultCode":"ValidCredentials",
   "brandLogoUri":"http:\/\/dev.virtualearth.net\/Branding\/logo_powered_by.png",
   "copyright":"Copyright © 2010 Microsoft and its suppliers. All rights reserved. This API cannot be accessed and the content and any results may not be used, reproduced or transmitted in any manner without express written permission from Microsoft Corporation.",
   "resourceSets":[
      {
         "estimatedTotal":1,
         "resources":[
            {
               "__type":"Location:http:\/\/schemas.microsoft.com\/search\/local\/ws\/rest\/v1",
               "bbox":[
                  47.635884282429323,
                  -122.13737419709076,
                  47.643609717570676,
                  -122.12208780290925
               ],
               "name":"1 Microsoft Way, Redmond, WA 98052-8300",
               "point":{
                  "type":"Point",
                  "coordinates":[
                     47.639747,
                     -122.129731
                  ]
               },
               "address":{
                  "addressLine":"1 Microsoft Way",
                  "adminDistrict":"WA",
                  "adminDistrict2":"King County",
                  "countryRegion":"United States",
                  "formattedAddress":"1 Microsoft Way, Redmond, WA 98052-8300",
                  "locality":"Redmond",
                  "postalCode":"98052-8300"
               },
               "confidence":"High",
               "entityType":"Address"
            }
         ]
      }
   ],
   "statusCode":200,
   "statusDescription":"OK",
   "traceId":"9ff2190c0a88428395c426abaa8cea34"
}

	
	/**
	 * @param args
	 * @throws IOException
	 * @throws URISyntaxException
	 */
	@Test
	public void testFindLocation() throws URISyntaxException, ClientProtocolException, IOException{
		
		//%20 代表url中的空格
		String query = "64111,3845 Broadway st".replaceAll(" ", "%20");
		String requestUri = "http://dev.virtualearth.net/REST/v1/Locations/"
			+ query
			+ "?o=json&key=AlBHPfpX9T4DUhBS0IxE-vOLnf3gGEUfqKw__a0uh_UUrMC6K0cSR4t89Xo0mGVP";
//		URI uri = new URI(
//				"http://dev.virtualearth.net/REST/v1/Locations/US/WA/98052/Redmond/1MicrosoftWay?o=json&key=AlBHPfpX9T4DUhBS0IxE-vOLnf3gGEUfqKw__a0uh_UUrMC6K0cSR4t89Xo0mGVP");
		URI uri = new URI(requestUri);
		HttpGet get = new HttpGet(uri);
		HttpClient httpclient = new DefaultHttpClient();
		HttpResponse response = httpclient.execute(get);
		StatusLine st = response.getStatusLine();
		if (st.getStatusCode() == HttpServletResponse.SC_OK) {
			InputStream ins = response.getEntity().getContent();
			
			BufferedReader br = new BufferedReader(new InputStreamReader(ins));
			StringBuilder sb = new StringBuilder();
			int i = 0;
			String b = br.readLine();
			while (b != null ) {
				i ++;
				sb.append(b);
				b = br.readLine();
			}
//			System.out.println(i);
//			System.out.println(sb.toString());
			JSONObject json = JSONObject.fromObject(sb.toString());
			System.out.println(json);
//			System.out.println(json.getJSONArray("resourceSets")
//					.getJSONObject(0).getJSONArray("resources")
//					.getJSONObject(0).getJSONObject("point")
//					.getJSONArray("coordinates").toString());
//			System.out.println(json.getJSONArray("resourceSets")
//					.getJSONObject(0).getJSONArray("resources")
//					.getJSONObject(0).getJSONObject("point").toString());
			System.out.println(json.getJSONArray("resourceSets")
					.getJSONObject(0).getJSONArray("resources")
					.getJSONObject(0).getJSONObject("address")
					.get("formattedAddress").toString());
		} else {
			System.out.println(st.getStatusCode());
		}
	}
	
	
	@Test
	public void testRoute() throws URISyntaxException, ClientProtocolException, IOException{
		//%20 代表url中的空格
//		String startAddress = "KANSAS";
////		String endAddress = "64111 3845 Broadway St".replaceAll(" ", "%20");
////		String endAddress = "64111,3845 Broadway St/KANSAS/MO/".replaceAll(" ", "%20");
//		String endAddress1 = "64111,3845 Broadway St/KANSAS/MO/"/*.replaceAll(" ", "%20")*/;
//		String endAddress = URLEncoder.encode(endAddress1, "utf-8");
//		
//		String startAddress = "Las Vegas";
		String startAddress = URLEncoder.encode("railroad ave","utf-8");
		String endAddress1 = "65014,railroad ave BRAND MO ";
		String endAddress = URLEncoder.encode(endAddress1, "utf-8");
		String routeRequest = "http://dev.virtualearth.net/REST/v1/Routes?wp.0="
			+ startAddress
			+ "&wp.1="
	//		+ endAddress
			+"48.74894"
			+ ","
			+ "-122.47949"
			+ "&routePathOutput=Points&output=json&key=AlBHPfpX9T4DUhBS0IxE-vOLnf3gGEUfqKw__a0uh_UUrMC6K0cSR4t89Xo0mGVP";
		URI uri = new URI(routeRequest);
		HttpGet get = new HttpGet(uri);
		HttpClient httpclient = new DefaultHttpClient();
		HttpResponse response = httpclient.execute(get);
		StatusLine st = response.getStatusLine();
		if (st.getStatusCode() == HttpServletResponse.SC_OK) {
			InputStream ins = response.getEntity().getContent();
			
			BufferedReader br = new BufferedReader(new InputStreamReader(ins));
			StringBuilder sb = new StringBuilder();
			int i = 0;
			String b = br.readLine();
			while (b != null ) {
				i ++;
				sb.append(b);
				b = br.readLine();
			}
			System.out.println("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+i);
			System.out.println(sb.toString());
			JSONObject json = JSONObject.fromObject(sb.toString());
			int itemsSize = json.getJSONArray("resourceSets")
			.getJSONObject(0).getJSONArray("resources")
			.getJSONObject(0).getJSONArray("routeLegs")
			.getJSONObject(0).getJSONArray("itineraryItems").size();
			for(int j = 0;j<itemsSize;j++){
				
				Double distanceKilometers = Double.valueOf(json.getJSONArray("resourceSets")
				.getJSONObject(0).getJSONArray("resources")
				.getJSONObject(0).getJSONArray("routeLegs")
				.getJSONObject(0).getJSONArray("itineraryItems")
				.getJSONObject(j).get("travelDistance").toString())/1.6093;
				BigDecimal   bigDistance   =   new   BigDecimal(distanceKilometers);
				Double distanceMile = bigDistance.setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue();
				
				String direction = json.getJSONArray("resourceSets")
				.getJSONObject(0).getJSONArray("resources")
				.getJSONObject(0).getJSONArray("routeLegs")
				.getJSONObject(0).getJSONArray("itineraryItems")
				.getJSONObject(j).getJSONObject("instruction")
				.get("text").toString();
//				.getJSONObject(j).get("travelDistance").toString();
				System.out.println(direction+" : "+distanceMile);
			}
		} else {
			System.out.println("else");
		}
	}
	
	@Test
	public void testNearBy() throws URISyntaxException, ClientProtocolException, IOException{
		
		//%20 代表url中的空格
		String query = "RAILROAD AVE".replaceAll(" ", "%20");
		String requestUri = "http://dev.virtualearth.net/REST/v1/Locations/"
			+ query
			+ "?o=json&key=AlBHPfpX9T4DUhBS0IxE-vOLnf3gGEUfqKw__a0uh_UUrMC6K0cSR4t89Xo0mGVP";
		URI uri = new URI(requestUri);
		HttpGet get = new HttpGet(uri);
		HttpClient httpclient = new DefaultHttpClient();
		HttpResponse response = httpclient.execute(get);
		StatusLine st = response.getStatusLine();
		if (st.getStatusCode() == HttpServletResponse.SC_OK) {
			InputStream ins = response.getEntity().getContent();
			
			BufferedReader br = new BufferedReader(new InputStreamReader(ins));
			StringBuilder sb = new StringBuilder();
			int i = 0;
			String b = br.readLine();
			while (b != null ) {
				i ++;
				sb.append(b);
				b = br.readLine();
			}
			JSONObject json = JSONObject.fromObject(sb.toString());
			System.out.println(json);
			Object[] point = json.getJSONArray("resourceSets")
					.getJSONObject(0).getJSONArray("resources")
					.getJSONObject(0).getJSONObject("point")
					.getJSONArray("coordinates").toArray();
		System.out.println(point[0]);
		System.out.println(point[1]);
//		// search nearBy
		 String baseUrl = "http://spatial.virtualearth.net/REST/v1/data/";
		 String accessID = "f20d8fcd56f84410ad46520ac2b48fe7";
		// String dataSourceName = "htpharmacy";
		 String dataSourceName =  "MSFT-Offices";
		 String entityTypeName = "Office";//f20d8fcd56f84410ad46520ac2b48fe7/
		 
//		 48.74894
//		 -122.47949
//		 String requestURI = "http://dev.virtualearth.net/REST/v1/Locations/Reading"
//		 		+"?culture=en-GB&output=json&key=AlBHPfpX9T4DUhBS0IxE-vOLnf3gGEUfqKw__a0uh_UUrMC6K0cSR4t89Xo0mGVP";
			String requestURI = "http://spatial.virtualearth.net/REST/v1/data/f20d8fcd56f84410ad46520ac2b48fe7/"
					+ dataSourceName
					+ "/"
					+ entityTypeName
					+ "?spatialFilter=nearby("
					+"48.74894"
					+ ","
					+ "-122.47949"//&$top=3
					+ ",1)&$format=json&key=AlBHPfpX9T4DUhBS0IxE-vOLnf3gGEUfqKw__a0uh_UUrMC6K0cSR4t89Xo0mGVP";
			System.out.println(requestURI);
//		 String requestURI = "http://spatial.virtualearth.net/REST/v1/data/f20d8fcd56f84410ad46520ac2b48fe7/"
//				+ dataSourceName
//				+ "/"
//				+ entityTypeName
//				+ "?filter=Locality Eq 'Reading' and Building Eq 'UK CAMPUS BLD5'&format=json&key=AlBHPfpX9T4DUhBS0IxE-vOLnf3gGEUfqKw__a0uh_UUrMC6K0cSR4t89Xo0mGVP";
//		 	String requestURI = "http://spatial.virtualearth.net/REST/v1/data/f20d8fcd56f84410ad46520ac2b48fe7/MSFT-Offices/Office?spatialFilter=nearby(51.45352028310299,-0.9630095958709717,10)&$format=json&jsonp=QueryCallBack&$top=3&key=AlBHPfpX9T4DUhBS0IxE-vOLnf3gGEUfqKw__a0uh_UUrMC6K0cSR4t89Xo0mGVP";
			URI uri2 = new URI(requestURI);
			HttpGet get2 = new HttpGet(uri2);
			HttpClient httpclient2 = new DefaultHttpClient();
			HttpResponse response2 = httpclient2.execute(get2);
			StatusLine st2 = response2.getStatusLine();
			if (st2.getStatusCode() == HttpServletResponse.SC_OK) {
				System.out.println("ok");
				InputStream ins2 = response2.getEntity().getContent();
				
				BufferedReader br2 = new BufferedReader(new InputStreamReader(ins2));
				StringBuilder sb2 = new StringBuilder();
				int i2 = 0;
				String b2 = br2.readLine();
				while (b2 != null ) {
					i2 ++;
					sb2.append(b2);
					b2 = br2.readLine();
				}
				System.out.println(i2);
				System.out.println(sb2.toString());
				JSONObject json2 = JSONObject.fromObject(sb2.toString());
				System.out.println("-------------------------");
				System.out.println(json2);
			}else{
				System.out.println("error");
			}
		}
	}
	
	@Test
	public void testNearBy2() throws URISyntaxException, ClientProtocolException, IOException{
		
//		// search nearBy
//		 String baseUrl = "http://spatial.virtualearth.net/REST/v1/data/";
//		 String accessID = "f20d8fcd56f84410ad46520ac2b48fe7";
		// String dataSourceName = "htpharmacy";
		 String dataSourceName =  "MSFT-Offices";
		 String entityTypeName = "Office";//f20d8fcd56f84410ad46520ac2b48fe7/
		 
//		 48.74894
//		 -122.47949
//		 String requestURI = "http://dev.virtualearth.net/REST/v1/Locations/Reading"
//		 		+"?culture=en-GB&output=json&key=AlBHPfpX9T4DUhBS0IxE-vOLnf3gGEUfqKw__a0uh_UUrMC6K0cSR4t89Xo0mGVP";
//			String requestURI = "http://spatial.virtualearth.net/REST/v1/data/f20d8fcd56f84410ad46520ac2b48fe7/"
//					+ dataSourceName
//					+ "/"
//					+ entityTypeName
//					+ "?spatialFilter=nearby('48.74894','-122.47949',1)&$format=json&key=AlBHPfpX9T4DUhBS0IxE-vOLnf3gGEUfqKw__a0uh_UUrMC6K0cSR4t89Xo0mGVP";
//			System.out.println(requestURI);
			//&$top=3
		 
		 
//		 queryString = baseUrl + accessID + "/" + dataSourceName + "/" + entityTypeName + "?spatialFilter=nearby(" + cpLat + "," + cpLon + "," + document.getElementById('txtRadius').value + ")&$format=json&jsonp=QueryCallBack&$top=" + document.getElementById('txtN').value + "&key=" + key;
//         document.getElementById("txtQuery").value = queryString;
//		 String requestURI = "http://spatial.virtualearth.net/REST/v1/data/f20d8fcd56f84410ad46520ac2b48fe7/"
//				+ dataSourceName
//				+ "/"
//				+ entityTypeName
//				+ "?filter=Locality Eq 'Reading' and Building Eq 'UK CAMPUS BLD5'&format=json&key=AlBHPfpX9T4DUhBS0IxE-vOLnf3gGEUfqKw__a0uh_UUrMC6K0cSR4t89Xo0mGVP";
//		 	String requestURI = "http://spatial.virtualearth.net/REST/v1/data/f20d8fcd56f84410ad46520ac2b48fe7/MSFT-Offices/Office?spatialFilter=nearby(48.74894,-122.47949,1)&$format=json&jsonp=QueryCallBack&$top=3&key=AlBHPfpX9T4DUhBS0IxE-vOLnf3gGEUfqKw__a0uh_UUrMC6K0cSR4t89Xo0mGVP";
		 	String requestURI = "http://spatial.virtualearth.net/REST/v1/data/f20d8fcd56f84410ad46520ac2b48fe7/MSFT-Offices/Office?spatialFilter=nearby(48.74894,-122.47949,1)&$format=json&key=AlBHPfpX9T4DUhBS0IxE-vOLnf3gGEUfqKw__a0uh_UUrMC6K0cSR4t89Xo0mGVP";
		 	URI uri = new URI(requestURI);
			HttpGet get = new HttpGet(uri);
			HttpClient httpclient = new DefaultHttpClient();
			HttpResponse response = httpclient.execute(get);
			StatusLine st2 = response.getStatusLine();
			System.out.println(st2.getStatusCode());
			if (st2.getStatusCode() == HttpServletResponse.SC_OK) {
				System.out.println("ok");
				InputStream ins = response.getEntity().getContent();
				
				BufferedReader br = new BufferedReader(new InputStreamReader(ins));
				StringBuilder sb = new StringBuilder();
				int i = 0;
				String b = br.readLine();
				while (b != null ) {
					i ++;
					sb.append(b);
					b = br.readLine();
				}
				System.out.println(i);
				System.out.println(sb.toString());
				JSONObject json2 = JSONObject.fromObject(sb.toString());
				System.out.println("-------------------------");
				System.out.println(json2);
			}else{
				System.out.println("error");
			}
		
	}
	
	
	@Test
	public void testBingMapSearcgByLatitudeAndLongitude() throws URISyntaxException, ClientProtocolException, IOException{
		String latitude="47.64054";
		String longitude="-122.12934";
		
	//	http://dev.virtualearth.net/REST/v1/Locations/47.64054,-122.12934?includeEntityTypes=countryRegion&o=xml&key=BingMapsKey

		String requestUri = "http://dev.virtualearth.net/REST/v1/Locations/"
			+latitude
			+","
			+longitude
			+ "?o=json&key=AlBHPfpX9T4DUhBS0IxE-vOLnf3gGEUfqKw__a0uh_UUrMC6K0cSR4t89Xo0mGVP";
		URI uri = new URI(requestUri);
		HttpGet get = new HttpGet(uri);
		HttpClient httpclient = new DefaultHttpClient();
		HttpResponse response = httpclient.execute(get);
		StatusLine st = response.getStatusLine();
		if (st.getStatusCode() == HttpServletResponse.SC_OK) {
			InputStream ins = response.getEntity().getContent();
			
			BufferedReader br = new BufferedReader(new InputStreamReader(ins));
			StringBuilder sb = new StringBuilder();
			int i = 0;
			String b = br.readLine();
			while (b != null ) {
				i ++;
				sb.append(b);
				b = br.readLine();
			}
			JSONObject json = JSONObject.fromObject(sb.toString());
			System.out.println(json);
			Object[] point = json.getJSONArray("resourceSets")
					.getJSONObject(0).getJSONArray("resources")
					.getJSONObject(0).getJSONObject("point")
					.getJSONArray("coordinates").toArray();
			String direction = json.getJSONArray("resourceSets")
			.getJSONObject(0).getJSONArray("resources")
			.getJSONObject(0).getJSONArray("routeLegs")
			.getJSONObject(0).getJSONArray("itineraryItems")
			.getJSONObject(i).getJSONObject("instruction")
			.get("text").toString();
		System.out.println(point[0]);
		System.out.println(point[1]);
		}
	}
	
	
	
	@Test
	public void testURLDecoder() throws UnsupportedEncodingException{
		String s = URLEncoder.encode(" ","UTF-8");
		System.out.println(s);
	}

}